package org.jeecg.modules.demo.DailyWork.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.DailyWork.entity.DailyWork;
import org.jeecg.modules.demo.DailyWork.service.IDailyWorkService;
import org.jeecg.modules.demo.hdpeersupervision.entity.HdPeerSupervisionVo;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


 /**
 * @Description: 日常工作信息
 * @Author: jeecg-boot
 * @Date:   2025-04-01
 * @Version: V1.0
 */
@Tag(name="日常工作信息")
@RestController
@RequestMapping("/DailyWork/dailyWork")
@Slf4j
public class DailyWorkController extends JeecgController<DailyWork, IDailyWorkService> {
	 @Autowired
	 private IDailyWorkService dailyWorkService;
	 @Autowired
	 private ISysDepartService sysDepartService;
	 @Autowired
	 private ISysUserRoleService sysUserRoleService;
	 @Autowired
	 private ISysUserService sysUserService;


	 /**
	  * 分页列表查询
	  *
	  * @param dailyWork
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "日常工作信息-分页列表查询")
	 @Operation(summary = "日常工作信息-分页列表查询", description = "日常工作信息-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<DailyWork>> queryPageList(DailyWork dailyWork,
												   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
												   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
												   HttpServletRequest req) {
		 QueryWrapper<DailyWork> queryWrapper = QueryGenerator.initQueryWrapper(dailyWork, req.getParameterMap());
		 Page<DailyWork> page = new Page<DailyWork>(pageNo, pageSize);
		 IPage<DailyWork> pageList = dailyWorkService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

//	 @Operation(summary = "整改监督信息-根据用户查询隐患信息", description = "整改监督信息-根据用户查询隐患信息")
//	 @GetMapping(value = "/listByUser")
//	 public Result<List<DailyWork>> listByUser(DailyWork dailyWork,
//														   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
//														   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
//														   HttpServletRequest req) {
//		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		 LambdaQueryWrapper<DailyWork> queryWrapper = new LambdaQueryWrapper<>();
//		 queryWrapper.eq(DailyWork::getCreateBy, loginUser.getUsername())
//				 .or().eq(DailyWork::getTransactors , loginUser.getUsername());
//		 List<DailyWork> list = dailyWorkService.list(queryWrapper);
//		 return Result.OK(list);
//	 }

	 @Operation(summary = "整改监督信息-根据用户查询隐患信息", description = "整改监督信息-根据用户查询隐患信息")
	 @GetMapping(value = "/listByUser")
	 public Result<IPage<DailyWork>> listByUser(DailyWork dailyWork,
												   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
												   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
												   HttpServletRequest req) {
		 QueryWrapper<DailyWork> queryWrapper = QueryGenerator.initQueryWrapper(dailyWork, req.getParameterMap());
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String departIds = loginUser.getDepartIds();
		 String departName = sysDepartService.getDepartNameById(departIds);
		 Page<DailyWork> page = new Page<DailyWork>(pageNo, pageSize);
		 if (loginUser.getRoleCode().equals("admin")||loginUser.getRoleCode().equals("leader")){

		 }else if (loginUser.getRoleCode().equals("department_management")){
			 queryWrapper.eq("transactors_dept", departName);

		 }else
		 {
			 queryWrapper.eq("transactors", loginUser.getRealname());
		 }
		 IPage<DailyWork> pageList = dailyWorkService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }


	 /**
	  * 添加
	  *
	  * @param dailyWork
	  * @return
	  */
	 @AutoLog(value = "日常工作信息-添加")
	 @Operation(summary = "日常工作信息-添加", description = "日常工作信息-添加")
	 @RequiresPermissions("DailyWork:daily_work:add")
	 @PostMapping(value = "/add")
	 public Result<String> add(@RequestBody DailyWork dailyWork) {
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String transactor = dailyWork.getTransactors();
		 String deptName = sysUserService.getDepIDsByReamName(transactor);
		 dailyWork.setCompletionStatus("未完成");
		 dailyWork.setTransactorsDept(deptName);
		 dailyWork.setReviewer(loginUser.getRealname());
		 dailyWorkService.save(dailyWork);

		 return Result.OK("添加成功！");
	 }

	 /**
	  * 添加
	  *
	  * @param dailyWork
	  * @return
	  */
	 @AutoLog(value = "日常工作信息-添加")
	 @Operation(summary = "日常工作信息-添加", description = "日常工作信息-添加")
	 @PostMapping(value = "/addExcel")
	 public Result<String> addExcel(@RequestBody DailyWork dailyWork) {
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String realname = loginUser.getRealname();
		 String transactorsDept = dailyWork.getTransactorsDept();
		 LambdaQueryWrapper<SysDepart> queryWrapper = new LambdaQueryWrapper<>();
		 queryWrapper.eq(SysDepart::getDepartName, transactorsDept);
		 SysDepart sysDepart = sysDepartService.getOne(queryWrapper);
		 LambdaQueryWrapper<SysUser> queryWrapper1 = new LambdaQueryWrapper<>();
		 queryWrapper1.eq(SysUser::getDepartIds, sysDepart.getId());
		 List<SysUser> sysUserList = sysUserService.list(queryWrapper1);
		 for (int i = 0; i < sysUserList.size(); i++) {
			 String roleId=sysUserRoleService.getRoleIdByUserId(sysUserList.get(i).getId());
			 if (roleId.equals("1939932967836213250")){
				 dailyWork.setTransactors(sysUserList.get(i).getRealname());
				 break;
			 }
		 }
		 //设置其他信息
		 dailyWork.setReviewer(realname);
		 dailyWorkService.save(dailyWork);

		 return Result.OK("添加成功！");
	 }


	 @GetMapping("/getUserIdByRealName")
	 public Result<String> getUserIdByRealName(@RequestParam(name="realName",required=false) String realName) {
		 String userId = sysUserService.getUserIdByRealName(realName);
		 return Result.ok(userId);
	 }



	 @Operation(summary = "根据时间查询", description = "根据时间查询")
	 @PostMapping(value = "/queryByTime")
	 public Result<Map<String, HdPeerSupervisionVo>> queryPageList2(@RequestBody JSONObject object, HttpServletRequest req) {
		 String remark = object.getString("remark");
		 Map<String, HdPeerSupervisionVo> result = new HashMap<>();

		 LocalDate date1;
		 LocalDate date2;
		 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

		 switch (remark) {
			 case "startEnd":
				 // 手动指定日期范围
				 String dateStr1 = object.getString("beganDate");
				 String dateStr2 = object.getString("endDate");
				 date1 = LocalDate.parse(dateStr1, formatter);
				 date2 = LocalDate.parse(dateStr2, formatter);
				 break;
			 case "day":
				 // 单个日期
				 //获取当天开始的日期
				 // 获取当前日期和时间
				 date1 = LocalDate.now();
				 date2 = date1;
				 break;
			 case "week":
				 // 本周（周一到周日）
				 LocalDate today = LocalDate.now();
				 date1 = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
				 date2 = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
				 break;
			 case "month":
				 // 本月
				 date1 = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
				 date2 = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
				 break;
			 case "year":
				 // 本年
				 date1 = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
				 date2 = LocalDate.now().with(TemporalAdjusters.lastDayOfYear());
				 break;
			 default:
				 return Result.error("无效的查询类型");
		 }
		 // 转换日期范围到LocalDateTime（含时间部分）
		 LocalDateTime startDateTime = date1.atStartOfDay();
		 LocalDateTime endDateTime = date2.atTime(LocalTime.MAX); // 23:59:59.999999999

		 List<SysDepart> departList = sysDepartService.list();
		 for (int i = 0; i < departList.size(); i++) {
			 HdPeerSupervisionVo hdPeerSupervisionVo = new HdPeerSupervisionVo();
			 Long total = dailyWorkService.count(new QueryWrapper<DailyWork>().eq("transactors_dept", departList.get(i).getDepartName())
					 .between("create_time", startDateTime, endDateTime));
			 if (total == 0L) {
				 continue;
			 }
			 Long notTotal = dailyWorkService.count(new QueryWrapper<DailyWork>().eq("transactors_dept", departList.get(i).getDepartName())
					 .between("create_time", startDateTime, endDateTime)
					 .eq("completion_status", "未完成"));
			 Long completeTotal = dailyWorkService.count(new QueryWrapper<DailyWork>().eq("transactors_dept", departList.get(i).getDepartName())
					 .between("create_time", startDateTime, endDateTime)
					 .eq("completion_status", "已完成"));
			 hdPeerSupervisionVo.setNotTotal(notTotal);
			 hdPeerSupervisionVo.setCompleteTotal(completeTotal);
			 if (total != 0L) {
				 double fillRate = (double) completeTotal / total;
				 //fillRate保留小数点后两位
				 fillRate=new BigDecimal(fillRate).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
				 hdPeerSupervisionVo.setFillRate(fillRate);
			 }
			 result.put(departList.get(i).getDepartName(), hdPeerSupervisionVo);

		 }
		 return Result.OK(result);

	 }

	 /**
	  * 编辑
	  *
	  * @param dailyWork
	  * @return
	  */
	 @AutoLog(value = "日常工作信息-编辑")
	 @Operation(summary = "日常工作信息-编辑", description = "日常工作信息-编辑")
	 @RequiresPermissions("DailyWork:daily_work:edit")
	 @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> edit(@RequestBody DailyWork dailyWork) {
		 dailyWorkService.updateById(dailyWork);
		 return Result.OK("编辑成功!");
	 }


	 /**
	  * 编辑
	  *
	  * @return
	  */
	 @AutoLog(value = "日常工作信息-流程信息添加到日常工作表中编辑")
	 @Operation(summary = "日常工作信息-流程信息添加到日常工作表中编辑", description = "日常工作信息-流程信息添加到日常工作表中编辑")
	 @RequestMapping(value = "/editWflow", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> editWflow(@RequestBody JSONObject jsObject) {
		 String instanceId = jsObject.getString("instanceId");
		 System.out.println("instanceId = " + instanceId);
		 String text= jsObject.getString("text");
		 System.out.println("text = " + text);
		 LambdaUpdateWrapper<DailyWork> lambdaWrapper = new LambdaUpdateWrapper<>();
		 lambdaWrapper.eq(DailyWork::getInstanceId, instanceId)
				 .set(DailyWork::getImplementationProgress,text);
		 dailyWorkService.update(lambdaWrapper);
		 return Result.OK("编辑成功!");
	 }


	 /**
	  * 通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "日常工作信息-通过id删除")
	 @Operation(summary = "日常工作信息-通过id删除", description = "日常工作信息-通过id删除")
	 @RequiresPermissions("DailyWork:daily_work:delete")
	 @DeleteMapping(value = "/delete")
	 public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
		 dailyWorkService.removeById(id);
		 return Result.OK("删除成功!");
	 }

	 /**
	  * 批量删除
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "日常工作信息-批量删除")
	 @Operation(summary = "日常工作信息-批量删除", description = "日常工作信息-批量删除")
	 @RequiresPermissions("DailyWork:daily_work:deleteBatch")
	 @DeleteMapping(value = "/deleteBatch")
	 public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		 this.dailyWorkService.removeByIds(Arrays.asList(ids.split(",")));
		 return Result.OK("批量删除成功!");
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "日常工作信息-通过id查询")
	 @Operation(summary = "日常工作信息-通过id查询", description = "日常工作信息-通过id查询")
	 @GetMapping(value = "/queryById")
	 public Result<DailyWork> queryById(@RequestParam(name = "id", required = true) String id) {
		 DailyWork dailyWork = dailyWorkService.getById(id);
		 if (dailyWork == null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(dailyWork);
	 }

	 /**
	  * 导出excel
	  *
	  * @param request
	  * @param dailyWork
	  */
	 @RequiresPermissions("DailyWork:daily_work:exportXls")
	 @RequestMapping(value = "/exportXls")
	 public ModelAndView exportXls(HttpServletRequest request, DailyWork dailyWork) {
		 return super.exportXls(request, dailyWork, DailyWork.class, "日常工作信息");
	 }

	 /**
	  * 通过excel导入数据
	  *
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequiresPermissions("DailyWork:daily_work:importExcel")
	 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 return super.importExcel(request, response, DailyWork.class);
	 }

	 @Autowired
	 private ISysBaseAPI sysBaseAPI;

	 @Operation(summary = "日常工作信息-工作催办", description = "日常工作信息-工作催办")
	 @PostMapping(value = "/sendMessage")
	 public Result<String> sendMessage(String names) throws Exception {
		 //将names进行分割
		 String[] nameArray = names.split(",");
		 for (String name : nameArray) {
			 String userName = sysUserService.getUserByReamName(name);
			 MessageDTO message = new MessageDTO("系统", userName,
					 "工作催办",
					 "你的工作还没完成，请及时处理，请及时处理!");
			 sysBaseAPI.sendSysAnnouncement(message);
		 }
		 return Result.OK("发送成功");
	 }

	 @Operation(summary = "日常工作-导出excel合并单元格", description = "日常工作-导出excel合并单元格")
	 @GetMapping(value = "/exportXlsMergeCells")
	 public Result<byte[]> exportXlsMergeCells(HttpServletRequest request, DailyWork dailyWork) throws IOException {
		 // Step.1 组装查询条件
		 QueryWrapper<DailyWork> queryWrapper =new QueryWrapper<>();
		 // 过滤选中数据
		 String selections = request.getParameter("selections");
//		 System.out.println("selections = " + selections);
		 String department = request.getParameter("department");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 System.out.println("selectionList = " + selectionList);
			 queryWrapper.in("id",selectionList);
		 }  else if (oConvertUtils.isNotEmpty(department)) {
			 List<String> departmentList = Arrays.asList(department.split(","));
			 queryWrapper.in("company_department",departmentList);
		 }

		 // Step.2 获取导出数据
		 List<DailyWork> exportList = dailyWorkService.list(queryWrapper);
		 // 2. 生成Excel字节数组
		 byte[] excelBytes = dailyWorkService.generateExcelBytes(exportList);
		 return Result.OK(excelBytes);
	 }

 }